package com.ruoyi.framework.web.service;


import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.entity.AppUser;
import com.ruoyi.common.core.domain.model.LoginAppUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.system.service.IAppUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class AppLoginService {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    private AppTokenService appTokenService;
    @Resource
    private IAppUserService appUserService;

    @Value("${wx.appId}")
    private String appId;
    @Value("${wx.appSecret}")
    private String appSecret;


    /**
     * 小程序登录
     * @param code
     * @return
     */
    public String wxLogin(String code,String encryptedData,String iv) throws Exception {
        //1根据code执行小程序登录获取 openId
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";
        String replaceUrl = url.replace("{0}",appId).replace("{1}",appSecret).replace("{2}",code);
        System.out.println(replaceUrl);
        JSONObject jsonObject = JSONObject.parseObject(HttpUtils.sendGet(replaceUrl));
        if(jsonObject.get("errcode")!=null){
            throw new ServiceException(String.format("获取微信授权信息失败，错误编码：%s，错误信息：%s",String.valueOf(jsonObject.get("errcode")),(String)jsonObject.get("errmsg")));
        }
        //2根据openId判断用户是否存在 不存在自动注册 openId对应数据库表user_name
        AppUser appUser = appUserService.selectAppUserByUserName(String.valueOf(jsonObject.get("openid")));
        if (appUser == null) {
            appUser = new AppUser();
            String phone =  decryptPhoneNumber(encryptedData,String.valueOf(jsonObject.get("session_key")),iv);
            appUser.setMobile(phone);
            appUser.setNickName("手作大师");
            appUser.setUserName(String.valueOf(jsonObject.get("openid")));
            appUserService.insertAppUser(appUser);
        }else{
            if(StringUtils.isEmpty(appUser.getMobile())){
                String phone =  decryptPhoneNumber(encryptedData,String.valueOf(jsonObject.get("session_key")),iv);
                appUser.setMobile(phone);
                appUserService.updateAppUser(appUser);
            }
        }
        //3生成token
        LoginAppUser loginAppUser = new LoginAppUser(appUser.getUserId(), appUser);
       // recordLoginInfo(loginAppUser.getUserId());
        return appTokenService.createAppToken(loginAppUser);
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    private void recordLoginInfo(Long userId) {
        AppUser appUser = new AppUser();
        appUser.setUserId(userId);
        appUser.setLoginIp(IpUtils.getIpAddr());
        appUser.setLoginDate(DateUtils.getNowDate());
        appUserService.updateAppUser(appUser);
    }
    public  String decryptPhoneNumber(String encryptedData, String sessionKey, String iv) throws Exception {
        try {
            // Base64解码 sessionKey 和 encryptedData
            byte[] sessionKeyDecoded = Base64.getDecoder().decode(sessionKey);
            byte[] encryptedDataDecoded = Base64.getDecoder().decode(encryptedData);
            byte[] ivDecoded = Base64.getDecoder().decode(iv);
            // 使用 sessionKey 解密
            SecretKeySpec secretKeySpec = new SecretKeySpec(sessionKeyDecoded, "AES");
            // 创建 AES 解密器
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");


            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new javax.crypto.spec.IvParameterSpec(ivDecoded));

            // 解密
            byte[] decryptedData = cipher.doFinal(encryptedDataDecoded);
            String decryptedString = new String(decryptedData, "UTF-8");
            JSONObject jsonObject =  JSONObject.parseObject(decryptedString);
            // 返回解密后的结果
            return jsonObject.getString("phoneNumber");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    public String savePhone(String encryptedData, String iv, String sessionKey) {
        try {
            // Base64解码 sessionKey 和 encryptedData
            byte[] sessionKeyDecoded = Base64.getDecoder().decode(sessionKey);
            byte[] encryptedDataDecoded = Base64.getDecoder().decode(encryptedData);
            byte[] ivDecoded = Base64.getDecoder().decode(iv);
            // 使用 sessionKey 解密
            SecretKeySpec secretKeySpec = new SecretKeySpec(sessionKeyDecoded, "AES");
            // 创建 AES 解密器
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new javax.crypto.spec.IvParameterSpec(ivDecoded));
            // 解密
            byte[] decryptedData = cipher.doFinal(encryptedDataDecoded);
            String decryptedString = new String(decryptedData, "UTF-8");
            JSONObject jsonObject =  JSONObject.parseObject(decryptedString);
            // 返回解密后的结果
            return jsonObject.getString("phoneNumber");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    public String checkLogin(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";
        String replaceUrl = url.replace("{0}",appId).replace("{1}",appSecret).replace("{2}",code);
        System.out.println(replaceUrl);
        JSONObject jsonObject = JSONObject.parseObject(HttpUtils.sendGet(replaceUrl));
        if(jsonObject.get("errcode")!=null){
            throw new ServiceException(String.format("获取微信授权信息失败，错误编码：%s，错误信息：%s",String.valueOf(jsonObject.get("errcode")),(String)jsonObject.get("errmsg")));
        }
        //2根据openId判断用户是否存在 不存在自动注册 openId对应数据库表user_name
        AppUser appUser = appUserService.selectAppUserByUserName(String.valueOf(jsonObject.get("openid")));
        if (appUser == null) {
            appUser = new AppUser();
            appUser.setNickName("手作大师");
            appUser.setUserName(String.valueOf(jsonObject.get("openid")));
            appUserService.insertAppUser(appUser);
        }
        if(StringUtils.isEmpty(appUser.getMobile())){
            return null;
        }
        //3生成token
        LoginAppUser loginAppUser = new LoginAppUser(appUser.getUserId(), appUser);
        return  appTokenService.createAppToken(loginAppUser);
    }
}
